#!/usr/bin/env ruby
gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
rails_root = File.expand_path(File.dirname(__FILE__) + "/..")
rspec_rails_gem_dir = nil
Dir["#{rails_root}/vendor/gems/*"].each do |subdir|
  rspec_rails_gem_dir = subdir if subdir.gsub("#{rails_root}/vendor/gems/","") =~ /^(\w+-)?rspec-rails-(\d+)/
end
rspec_rails_plugin_dir = File.expand_path("#{rails_root}/vendor/plugins/rspec-rails")

if rspec_rails_gem_dir && (test ?d, rspec_rails_plugin_dir)
  raise "\n#{'*'*50}\nYou have rspec installed in both vendor/gems and vendor/plugins\nPlease pick one and dispose of the other.\n#{'*'*50}\n\n"
end

if rspec_rails_gem_dir
  $LOAD_PATH.unshift("#{rspec_rails_gem_dir}/lib") 
elsif File.exist?(rspec_rails_plugin_dir)
  $LOAD_PATH.unshift("#{rspec_rails_plugin_dir}/lib")
end

require 'optparse'
require 'spec/rails/spec_server'

puts "Loading Rails environment"

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

if Rails::VERSION::STRING >= '2.2' && Rails.configuration.cache_classes
  warn <<-MESSAGE

#{'*'*50}

spec_server won't reload your classes if config.cache_classes
is set to true. Please modify environment/test.rb:

    config.cache_classes = false

#{'*'*50}
MESSAGE
end

options = Hash.new
parser = OptionParser.new
parser.on("-d", "--daemon")     {|ignore| options[:daemon] = true }
parser.on("-p", "--pid PIDFILE"){|pid|    options[:pid]    = pid  }
parser.parse!(ARGV)

if options[:daemon]
  ::Spec::Rails::SpecServer.daemonize(options[:pid])
else
  ::Spec::Rails::SpecServer.run
end
